<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElDialog, ElButton, ElInput, ElForm, ElFormItem, ElMessage, ElLoading, ElCard, ElTag, ElEmpty } from 'element-plus'
import axios from 'axios'

// 考核计划数据结构
const plans = ref([])
const loading = ref(false)

// 弹窗控制
const showPersonnelModal = ref(false)
const selectedPlan = ref(null)
const showResultModal = ref(false)
const selectedPerson = ref(null)
const resultForm = reactive({})
const resultFormRef = ref()

// 考核人员列表
const personnelList = ref([])
const personnelLoading = ref(false)

// 考核指标列表
const indicatorList = ref([])
const indicatorLoading = ref(false)

// 提交状态
const submitting = ref(false)

// 动态生成表单验证规则
const formRules = ref({})

// 生成表单验证规则
function generateFormRules() {
  const rules = {}
  indicatorList.value.forEach(indicator => {
    rules[`indicator_${indicator.indicatorId}`] = [
      { required: true, message: `请输入${indicator.indicatorName}分数`, trigger: 'blur' },
      { 
        validator: (rule, value, callback) => {
          if (value === '' || value === null || value === undefined) {
            callback(new Error(`请输入${indicator.indicatorName}分数`))
          } else {
            const numValue = parseFloat(value)
            if (isNaN(numValue)) {
              callback(new Error('请输入有效的数字'))
            } else if (numValue < 0 || numValue > 100) {
              callback(new Error('分数必须在0-100之间'))
            } else {
              callback()
            }
          }
        }, 
        trigger: 'blur' 
      }
    ]
    rules[`comment_${indicator.indicatorId}`] = [
      { required: true, message: `请输入${indicator.indicatorName}评语`, trigger: 'blur' }
    ]
  })
  formRules.value = rules
}

// 获取考核计划列表
async function fetchPlans() {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:8080/evaluator/getAllPln',
{
      headers: {
        'token' : localStorage.getItem("token")
      }
    }
    )
    if (response.data.code === 200) {
      plans.value = response.data.data || []
      if (plans.value.length === 0) {
        ElMessage.warning('暂无考核计划数据')
      } else {
        ElMessage.success('考核计划加载成功')
      }
    } else {
      ElMessage.error(response.data.msg || '获取考核计划失败')
    }
  } catch (error) {
    console.error('获取考核计划失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 获取考核人员列表
async function fetchPlanPersonnel(planId) {
  personnelLoading.value = true
  try {
    const response = await axios.get(`http://localhost:8080/evaluator/getPlanEmp?planId=${planId}`,
      {
      headers:{
        'token' : localStorage.getItem("token")
      }
    }
    )
    if (response.data.code === 200) {
      personnelList.value = response.data.data || []
      if (personnelList.value.length === 0) {
        ElMessage.warning('该计划下暂无考核人员')
      }
    } else {
      personnelList.value = []
      ElMessage.error(response.data.msg || '获取考核人员失败')
    }
  } catch (error) {
    console.error('获取考核人员失败:', error)
    personnelList.value = []
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    personnelLoading.value = false
  }
}

// 获取考核指标列表
async function fetchIndicators(planId) {
  indicatorLoading.value = true
  try {
    const response = await axios.get(`http://localhost:8080/evaluator/getIndicator`,
      {
        headers: {
          'token': localStorage.getItem("token")
        },
        params:{
          'planId':planId
        }
      }
    )
    if (response.data.code === 200) {
      indicatorList.value = response.data.data || []
      if (indicatorList.value.length === 0) {
        ElMessage.warning('该计划下暂无考核指标')
      }
      generateFormRules() // 生成表单验证规则
    } else {
      indicatorList.value = []
      ElMessage.error(response.data.msg || '获取考核指标失败')
      generateFormRules() // 生成表单验证规则
    }
  } catch (error) {
    console.error('获取考核指标失败:', error)
    indicatorList.value = []
    ElMessage.error('网络错误，请稍后重试')
    generateFormRules() // 生成表单验证规则
  } finally {
    indicatorLoading.value = false
  }
}

// 格式化日期显示
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取状态文本
function getStatusText(status) {
  if (status === -1) return '待开始'
  if (status === 1) return '进行中'
  return '已完成'
}

// 获取状态类型
function getStatusType(status) {
  if (status === -1) return 'warning'
  if (status === 1) return 'primary'
  return 'success'
}

async function openPersonnel(plan) {
  selectedPlan.value = plan
  showPersonnelModal.value = true

  // 获取该计划下的考核人员
  await fetchPlanPersonnel(plan.planId)
}

function closePersonnel() {
  showPersonnelModal.value = false
  selectedPlan.value = null
}

async function openResultInput(person) {
  selectedPerson.value = person
  console.log('选中的人员数据:', person) // 调试信息
  resultFormClear()
  showResultModal.value = true
  
  // 获取该计划的考核指标
  await fetchIndicators(selectedPlan.value.planId)
  
  // 如果没有考核指标，给出提示
  if (indicatorList.value.length === 0) {
    ElMessage.warning('该计划下暂无考核指标，无法录入考核结果')
  }
}

function closeResultInput() {
  showResultModal.value = false
  selectedPerson.value = null
}

function resultFormClear() {
  if (!selectedPlan.value) return
  // 清空表单
  Object.keys(resultForm).forEach(key => {
    resultForm[key] = ''
  })
  
  // 确保评语字段也被清空
  indicatorList.value.forEach(indicator => {
    resultForm[`comment_${indicator.indicatorId}`] = ''
  })
}

async function submitResult() {
  // 表单验证
  try {
    await resultFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善表单信息')
    return
  }

  // 验证必要的数据
  if (!selectedPlan.value || !selectedPerson.value) {
    ElMessage.error('数据不完整，请重新选择')
    return
  }
  
  console.log('提交时的人员数据:', selectedPerson.value) // 调试信息

  submitting.value = true
  try {
    // 构建符合后端接口的数据格式
    const indicatorScores = indicatorList.value.map(indicator => {
      const score = resultForm[`indicator_${indicator.indicatorId}`]
      const comment = resultForm[`comment_${indicator.indicatorId}`] || ''
      
      if (!score || score === '') {
        throw new Error(`请填写${indicator.indicatorName}的分数`)
      }
      
      // 验证分数是否为有效数字且在0-100范围内
      const numScore = parseFloat(score)
      if (isNaN(numScore)) {
        throw new Error(`请为${indicator.indicatorName}输入有效的数字`)
      }
      
      if (numScore < 0 || numScore > 100) {
        throw new Error(`${indicator.indicatorName}的分数必须在0-100之间`)
      }
      
      if (!comment || comment.trim() === '') {
        throw new Error(`请填写${indicator.indicatorName}的评语`)
      }
      
      return {
        indicatorId: indicator.indicatorId, // 指标ID
        score: numScore, // 确保分数是数字类型
        comment: comment.trim(), // 考核评语
        employeeId: selectedPerson.value.employeeId,
        planId: selectedPlan.value.planId // 考核计划ID
      }
    })

    const response = await axios.post('http://localhost:8080/evaluator/saveScore', indicatorScores, {
      headers: {
        'token': localStorage.getItem("token")
      }
    })
    console.log(response);
    
    if (response.data.code === 200) {
      ElMessage.success('考核结果提交成功')
      closeResultInput()
      closePersonnel()
    } else {
      ElMessage.error(response.data.msg || '提交失败')
    }
  } catch (error) {
    console.error('提交考核结果失败:', error)
    if (error.message && error.message.includes('请填写')) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    submitting.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchPlans()
})
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <h2 class="text-2xl font-bold">考核计划列表</h2>
      <el-button type="primary" @click="fetchPlans" :loading="loading">
        <i class="fas fa-sync-alt mr-2"></i>刷新
      </el-button>
    </div>

    <!-- 考核计划列表 -->
    <div v-loading="loading" class="grid gap-4">
      <el-card
        v-for="plan in plans"
        :key="plan.planId"
        class="hover:shadow-lg transition-shadow"
      >
        <div class="flex justify-between items-start">
          <div class="flex-1">
            <div class="flex items-center gap-3 mb-2">
              <h3 class="text-lg font-semibold text-gray-800">{{ plan.planName }}</h3>
              <el-tag :type="getStatusType(plan.status)" size="small">
                {{ getStatusText(plan.status) }}
              </el-tag>
            </div>
            <div class="text-sm text-gray-600 space-y-1">
              <p>
                <i class="fas fa-calendar mr-2"></i>考核周期：{{ plan.assessmentCycle }}
              </p>
              <p>
                <i class="fas fa-building mr-2"></i>考核对象：{{ plan.departmentName }}
              </p>
              <p>
                <i class="fas fa-clock mr-2"></i>考核时间：{{
                  formatDate(plan.startDate)
                }}
                - {{ formatDate(plan.endDate) }}
              </p>
            </div>
          </div>
          <div class="flex gap-2">
            <el-button
              v-if="plan.status === 1"
              type="primary"
              size="small"
              @click="openPersonnel(plan)"
            >
              <i class="fas fa-users mr-1"></i>查看人员
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 空状态 -->
    <el-empty v-if="!loading && plans.length === 0" description="暂无考核计划" />

    <!-- 人员弹窗 -->
    <el-dialog
      v-model="showPersonnelModal"
      :title="selectedPlan?.planName + ' - 考核人员'"
      width="500px"
      @close="closePersonnel"
    >
      <div class="text-sm text-gray-600 mb-4">
        <p>考核对象：{{ selectedPlan?.departmentName }}</p>
        <p>考核周期：{{ selectedPlan?.assessmentCycle }}</p>
      </div>

      <!-- 考核人员列表 -->
      <div v-loading="personnelLoading" class="bg-gray-50 p-4 rounded" style="max-height: 400px; overflow-y: auto;">
        <p class="text-gray-500 mb-3">该部门下的考核人员：</p>
        <div v-if="personnelList.length > 0" class="space-y-2">
          <div
            v-for="person in personnelList"
            :key="person.id"
            class="flex justify-between items-center p-3 bg-white rounded shadow-sm"
          >
            <div>
              <div class="font-medium text-gray-800">{{ person.name }}</div>
              <div class="text-sm text-gray-500">{{ person.position }}</div>
            </div>
            <el-button type="success" size="small" @click="openResultInput(person)">
              <i class="fas fa-edit mr-1"></i>录入结果
            </el-button>
          </div>
        </div>
        <el-empty v-else description="暂无考核人员" />
      </div>

      <template #footer>
        <el-button @click="closePersonnel">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 录入考核结果弹窗 -->
    <el-dialog
      v-model="showResultModal"
      :title="
        (selectedPerson?.name || '') +
        ' - ' +
        (selectedPlan?.planName || '') +
        ' 考核指标录入'
      "
      width="500px"
      @close="closeResultInput"
    >
      <div v-loading="indicatorLoading" style="max-height: 400px; overflow-y: auto;">
        <el-empty v-if="!indicatorLoading && indicatorList.length === 0" description="暂无考核指标" />
        <el-form
          v-else
          :model="resultForm"
          ref="resultFormRef"
          label-width="120px"
          :rules="formRules"
        >
          <el-form-item 
            v-for="indicator in indicatorList" 
            :key="indicator.indicatorId"
            :label="indicator.indicatorName" 
            :prop="`indicator_${indicator.indicatorId}`"
          >
            <div class="flex items-center gap-2">
              <el-input
                v-model="resultForm[`indicator_${indicator.indicatorId}`]"
                type="number"
                placeholder="请输入分数(0-100)"
                clearable
                :min="0"
                :max="100"
                class="flex-1"
              />
              <span class="text-sm text-gray-500">权重: {{ indicator.weight }}%</span>
            </div>
            <div class="text-xs text-gray-400 mt-1 mb-3">
              <span>类型: {{ indicator.indicatorType }}</span>
              <span class="ml-2">标准: {{ indicator.scoringStandard }}</span>
            </div>
          </el-form-item>
          
          <el-form-item 
            v-for="indicator in indicatorList" 
            :key="`comment_${indicator.indicatorId}`"
            :label="`${indicator.indicatorName}评语`" 
            :prop="`comment_${indicator.indicatorId}`"
          >
            <el-input
              v-model="resultForm[`comment_${indicator.indicatorId}`]"
              type="textarea"
              :rows="3"
              placeholder="请输入考核评语"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeResultInput">取消</el-button>
        <el-button 
          type="primary" 
          @click="submitResult" 
          :loading="submitting"
          :disabled="indicatorList.length === 0"
        >
          提交
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.el-card {
  border: 1px solid #e5e7eb;
}

.el-card:hover {
  border-color: #3b82f6;
}
</style>
